package com.dmitriyp.movie.editor;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IShowEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;

import com.dmitriyp.movie.ChangeEvent;
import com.dmitriyp.movie.EntityObserver;
import com.dmitriyp.movie.EntityObserver.ActionType;
import com.dmitriyp.movie.dao.IMovieManager;
import com.dmitriyp.movie.dao.MovieManagerFactory;
import com.dmitriyp.movie.mapping.Movie;

public class MovieEditor extends EditorPart implements IShowEditorInput {

	public final static String ID = "movie-db-editor";
	
	private Movie input;
	private MovieEditPage editPage;
	private boolean isDirty = false;
	private IMovieManager manager;
	
	@Override
	public void doSave(IProgressMonitor monitor) {
		if(input.getId() == null) {
			editPage.save();
			input = manager.add(input);
			EntityObserver.getInstance().fireEvent(new ChangeEvent(input, ActionType.ADD));
		}
	}

	@Override
	public void doSaveAs() {
		
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);
		manager = new MovieManagerFactory().createMovieManager();
	}

	@Override
	public boolean isDirty() {
		return isDirty;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	@Override
	public void createPartControl(Composite parent) {
		editPage = new MovieEditPage(parent);
		showEditorInput(getEditorInput());
	}
	
	@Override
	public void setFocus() {
	}
	
	@Override
	public void showEditorInput(IEditorInput editorInput) {
		if(editorInput instanceof MovieEditorInput) {
			input = ((MovieEditorInput)editorInput).getMovie();
			isDirty = input != null && input.getId() == null;
			firePropertyChange(IEditorPart.PROP_DIRTY);
			editPage.setValue(input);
			editPage.refresh();
		}
	}

}
